import { routerRedux } from 'dva/router';
import { message } from 'antd';
import {
    getTypeList, getVideoList, updateVideo, videoList, addInformation, getTreeListVideo, getVideoListVideo, classList,
    informationInfo, usedModule, serviceList,liveList,videothemeList, auditVideo, getlistTypePlate, getInfoHistory, getInfoHistoryDetail, deleteInfoHistory,getConfig,getAreaList,updateLogData

} from '../services/fetch'
import Http from '../utils/http.js'
import {
    themeList
} from '../services/information'
import {
    informationThemeInfo, updateInformation
} from '../services/theme'
import moment from 'moment';
const init = {
    default_forward_num: '',
    default_scan_num: '',
    default_thumbs_up_num: '',
    external_links: '',
    is_comment: 1,
    is_original: 1,
    scan_num: 0,
    forward_num: 0,
    thumbs_up_num: 0,
    is_check_comment: 0,
    is_ad: 0,
    is_reprint: 0,
    key_word: '',
    plate_id: '',
    position: '',
    reporter: '',
    resource: '',
    video_intro: '',
    video_title: '',
    video_img: '',
    video_src: '',
    mchType: 'editor',
    
}

export default {
    namespace: 'add',

    state: {
        plateList: [        //右侧分类数据
        ],
        articleData: [      //多个文稿数据集合
        ],
        pushData: [],       //左侧已发布视频
        pushDataEnd: 0,       //左侧已发布视频是否最后一页
        gltjData: [],        //关联推荐 视频
        currentActiveArticle: 1, //当前选中文稿
        treeList: [],              //资讯分类
        treeListVideo: [],         //视频分类
        dataSource: {},              //数据列表
        dataSourceRef: [],
        informationInfo: {},   //详情  修改 复制
        classList: [],
        banner_plate_name: '',
        mchType: 'editor',
        activeKey: '1',//当前文章类型
        uploadImageList: [],//当前图集图片列表
        allDataSource: [
            { title: '新建', content: {}, key: '1' },
        ],
        configJson: {},
        transcode_data:[],//转码数据
        styleLibrary:[{}],
        spinning:false,
        areaList: []
    },

    subscriptions: {
        setup({ dispatch, history }) {  // eslint-disable-line
        },
    },

    effects: {
        /**
         * 获取魔盒样式库
         */
        *getStyleLibrary({ data }, { call, put,select }) {
            yield put({
                type:'setSpin',
                data: true
            })   
            const configJson = yield select(state => state.add.configJson);
            var result=[]
           yield Http(configJson.mhUrl,'post',{
               "signstr":data.signstr
           })
           .then((res)=>{ 
              if(res.code === 200){ 
              result = res.data  
             } 
              if(res.code === 500){
               message.error(res.msg)
            }
            })
           .catch((err)=>{
            console.log(err)
          })        
            yield put({
                type:'setStyleLibrary',
                data: result
            })   
            yield put({
                type:'setSpin',
                data: false
            })      
        },
        /**
         * 提交审核
         * @param {} param0
         * @param {*} param1
         */
        *getAuditVideo({ data }, { call, put }) {
            const list = yield call(auditVideo, data);
            if (list.data.code === 200) {
                //设置localStorage 在/view/add/Video/video.js 中监听storage变化，实现跨页面通信
                localStorage.setItem('submit', Date.parse(new Date()));
                message.success('提交审核成功')
            } else {
                message.error('提交审核失败')
            }
        },
        *pushVideo({ payload }, { call, put }) {
            yield put(routerRedux.push('/video'));
        },
        *auditVideo({ payload }, { call, put, select }) {
            const articleData = yield select(state => state.add.articleData);
            if (articleData.length == 1) {
                yield put(routerRedux.push('/video'));
            } else {
                yield put({ type: 'pushCheckVideo' });
            }
        },
        *addView({ payload }, { call, put }) {
            yield put({ type: 'addInit' });
            yield put(routerRedux.push('/Add'));
        },
        //获取版面样式
        *getBanMian({ payload, callback }, { call, put, select }) {
            const list = yield call(getlistTypePlate);
            const data = []
            list && list.data && list.data.data && list.data.data.map((item, index) => {
                let disabled = false;
                if (item.children) {
                    disabled = true;
                }
                if (item.is_other || item.url) {
                    disabled = true;
                }

                let obj = {
                    key: String(index),
                    plate_id: item.plate_id,
                    title: item.plate_name,
                    sub_title: item.sub_plate_name,
                    children: item.children ? item.children : [],
                    value: item.plate_id,
                    disabled: disabled,
                    template_conf: item.template_conf
                }
                if (item.children) {
                    item.children.map((i, ins) => {
                        let obj2 = {
                            key: String(index) + '-' + ins,
                            plate_id: i.plate_id,
                            title: i.plate_name,
                            sub_title: i.sub_plate_name,
                            value: i.plate_id,
                            template_id: i.template_id,
                            template_conf: i.template_conf
                        }
                        item.children[ins] = obj2
                    })
                }
                data[index] = obj
            })
            if (callback) callback(data)
            yield put({ type: 'setPlate', data: data });
        },
        /**
         * 初始化
         */
        *addInit({ payload }, { call, put, select }) {
            const list = yield call(getTypeList);
            const videoList = yield call(getVideoList, {
                index: 1,
                plate_id: ''
            });
            // yield put({ type: 'setPlate', data: list.data.data });
            yield put({ type: 'initPush', data: videoList.data.data.list });
            const initTableName = yield select(state => state.video.initTableName);
            let data = { ...init };
            data.plate_id = initTableName
            yield put({ type: 'init', data: data });
        },
        /**
         * 提交审核回调，需要通过yield 同步操作确保审核时 video_id 存在
         */
        *addVideoCallback({ payload, }, { call, put, select }) {
            let reducData = {
                video_id: payload.video_id,
            }
            yield put({ type: 'setFields', data: reducData });

            if (typeof payload.callback == 'function') {
                yield payload.callback();
            }
        },
        /**
         * 刷新页面
         */
        *refreshPage({ data }, { call, put, select }) {
            const list = yield call(getTypeList);
            // yield put({ type: 'setPlate', data: list.data.data });
            yield put({ type: 'init', data: data });
        },
        /**
         * 已发布树选择
         */
        *treeOnChange({ data }, { call, put, select }) {
            const videoList = yield call(getVideoList, {
                index: data.index ? data.index : 1,
                plate_id: data.plate_id,
                state: 1,
                module_name: 1,
                page_size: 20
            });

            if (data.index && data.index >= videoList.data.data.total_page) {

                yield put({ type: 'initPushEnd', data: 1 });
            } else {
                yield put({ type: 'initPushEnd', data: 0 });
            }
            yield put({ type: 'initPush', data: videoList.data.data.list });
        },
        /**
         * 获取详情
         */
        *edit({ data, callback }, { call, put, select }) {
            const list = yield call(informationInfo, {
                information_id: data
            });
            if (list.data.code === 200) {
                yield put({ type: 'saveInformationInfo', data: list.data.data });
            }
            if (callback) callback(list.data.data)
        },
        /**
         * 获取详情
         */
        *editGetThemeDetail({ data, callback }, { call, put, select }) {
            const list = yield call(informationThemeInfo, {
                information_id: data
            });
            if (list.data.code === 200) {
                yield put({ type: 'saveInformationInfo', data: list.data.data });
            }
            if (callback) callback(list.data.data)
        },


        /**
         * 复制
         */
        *copy({ data }, { call, put, select }) {
            const info = yield call(videoList, {
                index: 1,
                video_ids: data
            });

            const list = yield call(getTypeList);
            const videoListData = yield call(getVideoList, {
                index: 1,
                plate_id: ''
            });
            // yield put({ type: 'setPlate', data: list.data.data });
            yield put({ type: 'initPush', data: videoListData.data.data.list });
            yield put({ type: 'copyInit', data: info.data.data.list });
        },
        /**
        * 新增咨询
        */
        *addInformation({ data, callback }, { call, put, select }) {
            if (data.crond_time) {
                data.crond_time = moment(data.crond_time).format('YYYY-MM-DD HH:mm:ss');
            }
            if (data.lower_crond_time) {
                data.lower_crond_time = moment(data.lower_crond_time).format('YYYY-MM-DD HH:mm:ss');
            }

            const res = yield call(addInformation, data);
            if (res.data.code === 200) {
                if (!callback) {
                    message.success(res.data.msg)
                }
                const initTableName = yield select(state => state.video.initTableName);
                let dataAugment = {
                    index: 1,
                    plate_id: initTableName
                }
                yield put({ type: 'getTableList', payload: { dataAugment: dataAugment } });
                localStorage.setItem('submit', Date.parse(new Date()));
                yield put({
                    type: "edit",
                    data: res.data.data
                })
                yield put({ 
                    type: 'getInfoHistory',
                    payload: {
                        information_id: res.data.data
                    }
                });

                // window.PubSub.publish('tabRemove');这里取消关闭新建页面
            } else {
                message.error(res.data.msg)
            }
            if (callback) {
                yield call(callback, res.data)
            }

        },
        //获取资讯分类列表
        *getTreeList({ payload, callback }, { call, put, select }) {
            const list = yield call(getTypeList);
            const data = []
            list && list.data && list.data.data && list.data.data.map((item, index) => {
                let obj = {
                    key: '1' + "-" + String(index),
                    plate_id: item.plate_id,
                    title: item.plate_name,
                    children: item.children ? item.children : '',
                    value: String(index),
                    template_id: item.template_id,
                }
                if (item.children) {
                    item.children.map((i, ins) => {
                        let obj2 = {
                            key: '1' + "-" + String(index) + '-' + ins,
                            plate_id: i.plate_id,
                            title: i.plate_name,
                            value: String(index) + '-' + ins,
                            template_id: i.template_id,
                        }
                        item.children[ins] = obj2
                    })
                }
                data[index] = obj
            })
            yield put({ type: 'updateTreeList', data: data });
        },
        //获取视频分类列表
        *getTreeListVideo({ payload, callback }, { call, put, select }) {
            const list = yield call(getTreeListVideo);
            const data = []
            list && list.data && list.data.data && list.data.data.map((item, index) => {
                let obj = {
                    key: 0 + "-" + String(index),
                    plate_id: item.plate_id,
                    title: item.plate_name,
                    children: item.children ? item.children : '',
                    value: item.plate_id,
                    plate_name: item.plate_name
                }
                if (item.children) {
                    item.children.map((i, ins) => {
                        let obj2 = {
                            key: 0 + "-" + String(index) + '-' + ins,
                            plate_id: i.plate_id,
                            title: i.plate_name,
                            value: i.plate_id,
                            plate_name: item.plate_name
                        }
                        item.children[ins] = obj2
                    })
                }
                data[index] = obj
            })
            yield put({ type: 'updateTreeListVideo', data: data });
        },
        /**
         * 获取资讯列表
         */
        *getTableList({ payload }, { call, put, select }) {
            const list = yield call(getVideoList, payload.dataAugment);
            yield put({ type: 'updateTableList', data: list.data.data });
            yield put({ type: 'updateTableListRef', data: list.data.data });
        },
        /**
         * 获取专题列表
         */
        *themeList({ payload }, { call, put, select }) {
            const list = yield call(themeList, payload.dataAugment);
            list.data.data.list.forEach((item, key) => {
                item.title = item.theme_name;
                item.img = item.theme_img;
                item.id = item.theme_id;
            })
            yield put({ type: 'updateTableList', data: list.data.data });
            yield put({ type: 'updateTableListRef', data: list.data.data });
        },
        /**
         * 获取发现列表
         */
        *serviceList({ payload }, { call, put, select }) {
            const list = yield call(serviceList, payload.dataAugment);
            list.data.data.list.forEach((item, key) => {
                item.title = item.service_name;
                item.img = item.service_img;
                item.id = item.service_id;
            })
            yield put({ type: 'updateTableList', data: list.data.data });
            yield put({ type: 'updateTableListRef', data: list.data.data });
        },
        /**
         * 获取直播列表
         */
        *liveList({ payload }, { call, put, select }) {
            const list = yield call(liveList,payload.baseUrl,payload.access_key,  payload.dataAugment);
            if (list.data&&list.data.data&&list.data.data.data) {
                list.data.data.data.forEach((item, key) => {
                    item.title = item.name;
                    item.img = item.live_cover;
                    item.id = item.id;
                })
                yield put({ type: 'updateTableList', data: list.data.data.data });
                yield put({ type: 'updateTableListRef', data: {list:list.data.data.data,total:list.data.data.total} });
            }else{
                yield put({ type: 'updateTableList', data: [] });
                yield put({ type: 'updateTableListRef', data: {list:[],total:0} }); 
            }
        },
         /**
         * 获取直播列表
         */
        *videothemeList({ payload }, { call, put, select }) {
            const list = yield call(videothemeList, payload.dataAugment);
            if (list.data&&list.data.data&&list.data.data.data) {
            list.data.data.data.forEach((item, key) => {
                item.title = item.theme_name;
                item.img = item.theme_img;
                item.id = item.theme_id;
            })
            yield put({ type: 'updateTableList', data: list.data.data.data });
            yield put({ type: 'updateTableListRef', data: {list:list.data.data.data,total:list.data.data.total} });
            }else{
                yield put({ type: 'updateTableList', data: [] });
                yield put({ type: 'updateTableListRef', data: {list:[],total:0} }); 
            }
        },
        /**
         * 获取视频列表
         */
        *getTableListVideo({ payload }, { call, put, select }) {
            const list = yield call(getVideoListVideo, payload.dataAugment);
            yield put({ type: 'updateTableListRef', data: list.data.data });
        },


        /**
         * 修改资讯
         */
        *editInformation({ data, toShenHe, callback }, { call, put, select }) {

            if (data.crond_time) {
                data.crond_time = moment(data.crond_time).format('YYYY-MM-DD HH:mm:ss');
            }
            if (data.lower_crond_time) {
                data.lower_crond_time = moment(data.lower_crond_time).format('YYYY-MM-DD HH:mm:ss');
            }

            const list = yield call(updateVideo, data);
            console.log(list,'12345')
            localStorage.setItem('treeSelectedValue', data.plate_id);
            localStorage.setItem('edit', Date.parse(new Date()));
            if (list.data.code == 200) {
                // if(toShenHe === 0){
                //     message.success(list.data.msg)
                // }
                if (callback) {
                    yield call(callback, list.data.code)
                }
                yield put({ 
                    type: 'getInfoHistory',
                    payload: {
                        information_id: data.information_id
                    }
                });
            } else {
                message.error(list.data.msg);
            }


        },
        /**
        * 修改专题资讯
        */
        *updateInformation({ data, callback }, { call, put, select }) {

            if (data.crond_time) {
                data.crond_time = moment(data.crond_time).format('YYYY-MM-DD HH:mm:ss');
            }
            if (data.lower_crond_time) {
                data.lower_crond_time = moment(data.lower_crond_time).format('YYYY-MM-DD HH:mm:ss');
            }
            const list = yield call(updateInformation, data);

            if (list.data.code == 200) {
                localStorage.setItem('localSelectedThemeId', list.data.data.theme_id);
                localStorage.setItem('themeSubmit', Date.parse(new Date()));
                if (callback) {
                    yield call(callback, list.data.code)
                } else {
                    message.success(list.data.msg)
                }

            } else {
                message.error(list.data.msg);
            }

        },
        /**
         * 引用
         */
        *usedModule({ payload, callback }, { call, put, select }) {
            const list = yield call(usedModule, payload.data);
            if (list.data.code === 200) {
                message.success(list.data.msg)
                if (callback) callback()
                const videoList = yield call(getVideoList, payload.dataAugment);
                yield put({ type: 'video/updateTableList', data: videoList.data.data });
            } else {
                message.error(list.data.msg)
            }
        },
        /**
         * 获取分类列表
         */
        *classList({ payload }, { call, put }) {
            let list = yield call(classList);
            if (list.data.code === 200) {
                yield put({ type: 'saveClassList', data: list.data.data })
            }
        },
        /**
         * 获取区域列表
         */
        *areaList({ payload }, { call, put }) {
            let list = yield call(getAreaList);
            if (list.data.code === 200) {
                yield put({ type: 'saveAreaList', data: list.data.data })
            }
        },
        /**
         * 获取资讯稿件历史列表
         * @param {*} param0 
         * @param {*} param1 
         */
        *getInfoHistory({ payload }, { call, put }) {
            let res = yield call(getInfoHistory, payload);
            if(res.data.code == 200){
                yield put({
                    type: "setInfoHistoryList",
                    payload: {
                        infoHistoryList: res.data.data
                    }
                })
            }
        },
        *getCurrentDraft({ payload, callback }, { call, put }) {
            let res = yield call(getInfoHistoryDetail, payload);
            console.log("res", res);
            if(res.data.code == 200) {
                // let data = res.data.data;
                yield call(callback, res.data.data.old.new_data_back)
                yield put({
                    type: "setCurrentDraft",
                    payload: {
                        currentInfoDraft: res.data.data.old.new_data_back
                    }
                })
            }
        },
        *deleteDraft({ payload, callback }, { call, put, select }){
            const informationInfo = yield select(state => state.add.informationInfo);
            let res = yield call(deleteInfoHistory, payload);
            console.log(res)
            if(res.data.code == 200){
                message.success("历史版本删除成功！");
                yield put({
                    type: "getInfoHistory",
                    payload: {
                        information_id: informationInfo.information_id
                    }
                })
            }else{
                message.error(res.data.msg);
            }
        },
        *updateDraft({ payload, callback }, { call, put, select }){
            const informationInfo = yield select(state => state.add.informationInfo);
            let res = yield call(updateLogData, payload);
            console.log(res)
            if(res.data.code == 200){
                message.success("修改成功！");
                yield put({
                    type: "getInfoHistory",
                    payload: {
                        information_id: informationInfo.information_id
                    }
                })
            }else{
                message.error(res.data.msg);
            }
        }

    },

    reducers: {
        setSpin(state, action) {
            return { ...state, spinning: action.data }
        },
        setStyleLibrary(state, action) {
            return { ...state, styleLibrary: action.data }
        },
        saveAllDataSource(state, action) {
            return { ...state, allDataSource: action.data };
        },
        saveMchType(state, action) {
            return { ...state, mchType: action.data };
        },
        saveClassList(state, action) {
            return { ...state, classList: action.data };
        },
        saveAreaList(state, action) {
            return { ...state, areaList: action.data };
        },
        saveBannerPlateID(state, data) {
            return { ...state, banner_plate_name: data.data };
        },
        saveInformationInfo(state, action) {
            return { ...state, informationInfo: action.data };
        },
        updateTableList(state, action) {
            return { ...state, dataSource: action.data };
        },
        updateTableListRef(state, action) {
            return { ...state, dataSourceRef: action.data };
        },
        updateTreeList(state, action) {
            return { ...state, treeList: action.data };
        },
        updateTreeListVideo(state, action) {
            return { ...state, treeListVideo: action.data };
        },
        setPlate(state, action) {
            return { ...state, plateList: action.data }
        },
        initPush(state, action) {
            return { ...state, pushData: action.data }
        },
        initPushEnd(state, action) {
            return { ...state, pushDataEnd: action.data }
        },
        pushClick(state, action) {
            // console.log(state);
            if (!state.gltjData) {
                state.gltjData = []
            }
            return { ...state, gltjData: state.gltjData.concat(action.data) }
        },
        resetPushClick(state, action) {
            return { ...state, gltjData: [] }
        },
        setActiveKey(state, action) {
            return { ...state, activeKey: action.data }
        },
        setUploadImageList(state, action) {
            return { ...state, uploadImageList: action.data }
        },

        setPushClick(state, action) {
            return { ...state, gltjData: action.data }
        },
        close(state, action) {
            let gltjData = state.gltjData;
            delete gltjData[action.key]
            return { ...state, gltjData: gltjData }
        },
        resetSetData(state, action) {
            return { ...state, articleData: [{ data: undefined, id: 123321 }] }
        },
        setData(state, action) {

            let data = state.articleData;
            data.forEach((item, key) => {
                if (item.id == state.currentActiveArticle) {
                    delete action.data.video_id;
                    delete action.data.plate_id;
                    item.data = { ...item.data, ...action.data }
                }
            })
            return { ...state, articleData: data }
        },
        editInit(state, action) {
            let data = [];
            action.data.forEach((item, k) => {
                let obj = {
                    id: k + 1,
                    data: item
                }
                data.push(obj);
            })
            return { ...state, articleData: data, gltjData: [], currentActiveArticle: 1 };
        },
        copyInit(state, action) {
            let data = [];
            action.data.forEach((item, k) => {
                delete item.video_id;
                let obj = {
                    id: k + 1,
                    data: item
                }
                data.push(obj);
            })
            return { ...state, articleData: data, gltjData: [], currentActiveArticle: 1 };
        },
        init(state, action) {
            let data = [];
            let obj = {
                id: 1,
                data: action.data
            };
            data.push(obj)
            return { ...state, articleData: data, gltjData: [], currentActiveArticle: 1 };
        },
        reSet(state, action) {
            let key;
            let { articleData } = state;
            articleData.forEach((item, k) => {
                if (item.id == state.currentActiveArticle) {
                    key = k;
                    item.data = init;
                }
            })
            return { ...state, articleData: articleData };
        },
        add(state, action) {
            let data = state.articleData;
            let obj = {
                id: state.articleData[state.articleData.length - 1].id + 1,
                data: init
            };
            data.forEach(item => {
                item.active = false
            });
            data.push(obj)
            return { ...state, articleData: data };
        },
        select(state, action) {
            return { ...state, currentActiveArticle: action.data.id };
        },
        pushCheckVideo(state, action) {   //提交审核删除
            let key;
            let { articleData } = state;
            articleData.forEach((item, k) => {
                if (item.id == state.currentActiveArticle) {
                    key = k;
                }
            })
            let data = state.articleData;
            let currentActiveArticle = state.currentActiveArticle;
            if (data[key].id == currentActiveArticle) {
                if (data.length == key + 1) { //如果当前选中的为最后一个稿件，那么选中前一个
                    currentActiveArticle = data[key - 1].id;
                } else {                        //否则如果为第一个稿件，那么选中后一个
                    currentActiveArticle = data[key + 1].id;
                }
            }
            data.splice(key, 1);
            return { ...state, articleData: data, currentActiveArticle: currentActiveArticle };
        },
        delete(state, action) {    //header头直接删除
            let data = state.articleData;
            let currentActiveArticle = state.currentActiveArticle;
            if (data.length == 1) {
                message.info('最后一个稿件不能删除');
                return { ...state };
            }
            let key = action.data.key;
            if (data[key].id == currentActiveArticle) {
                if (data.length == key + 1) { //如果当前选中的为最后一个稿件，那么选中前一个
                    currentActiveArticle = data[key - 1].id;
                } else {                        //否则如果为第一个稿件，那么选中后一个
                    currentActiveArticle = data[key + 1].id;
                }
            }
            data.splice(action.data.key, 1);
            return { ...state, articleData: data, currentActiveArticle: currentActiveArticle };
        },
        setFields(state, action) {
            let data = state.articleData;
            // data.forEach((item, key) => {
            //     if (item.id == state.currentActiveArticle) {
            //         let allData = { ...item.data, ...action.data }
            //         item.data = allData;
            //     }
            // })

            return { ...state, articleData: data }

        },
        setInfoHistoryList(state, action){
            return {
                ...state,
                ...action.payload
            }
        },
        setCurrentDraft(state, action){
            let data = state.articleData;
            return { ...state, ...action.payload}; 
        },
        configJson(state, action) {
            return { ...state, configJson: action.data }
        },
        setTranscodeData(state, action) {
            return { ...state, transcode_data: action.data }
        }

    },
};
